package org.projectback.listener;

import com.zaxxer.hikari.HikariDataSource;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.event.EventListener;
import org.springframework.data.redis.connection.RedisConnectionCommands;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.sql.SQLException;

/**
 * 执行服务器启动后的初始化工作
 *
 * @author K·K
 * @version 1.0
 * @Date 2025/10/26
 */
@Slf4j
@Component
public class ApplicationEventListener {
    @Resource
    HikariDataSource hikariDataSource;
    @Resource
    RedisTemplate<String, Object> redisTemplate;

    @EventListener(ApplicationReadyEvent.class)
    public void onApplicationEvent(@NotNull ApplicationReadyEvent event) {
        warmConnectionPool(hikariDataSource);
        warmRedis(redisTemplate);
    }

    private boolean warmRedis(RedisTemplate<String, Object> redisTemplate) {
        long currentTimeMillis = System.currentTimeMillis();
        log.info("Warming Redis.....");
        redisTemplate.execute((RedisCallback<Object>) RedisConnectionCommands::ping);
        log.info("Redis has been warmed! consuming:{}ms", System.currentTimeMillis() - currentTimeMillis);
        return true;
    }

    private boolean warmConnectionPool(HikariDataSource hikariDataSource) {
        try {
            long currentTimeMillis = System.currentTimeMillis();
            log.info("Warming up connection pool...");
            hikariDataSource.getConnection();
            log.info("Connection pool has been warmed! consuming:{}ms", System.currentTimeMillis() - currentTimeMillis);
            return true;
        } catch (SQLException e) {
            return false;
        }
    }


}
